package com.para.esc.web.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

public class HttpsRequestUtil {

    static class miTM implements javax.net.ssl.TrustManager,
            javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }
    /**
     * 根据请求的URL是https还是http请求数据
     * @param sendUrl
     * @param param
     * @return
     * @throws Exception
     */
    public static String getResult(String sendUrl, String param)
            throws Exception {
        if(sendUrl.startsWith("https")){
            return getResultByHttps(sendUrl, param);
        }
        return getResultByHttp(sendUrl, param);
    }

    private static String getResultByHttps(String sendUrl, String param)
            throws NoSuchAlgorithmException, KeyManagementException,
            IOException {
        javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
        javax.net.ssl.TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        // javax.net.ssl.SSLContext sc =
        // javax.net.ssl.SSLContext.getInstance("SSL");
        javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
                .getInstance("SSLv3");

        sc.init(null, trustAllCerts, null);
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
                .getSocketFactory());

        HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);

        DataOutputStream out = null;
        BufferedReader reader = null;
        String result = "";
        URL url = null;
        HttpsURLConnection conn = null;
        try {
            url = new URL(sendUrl);
            conn = (HttpsURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-type",
                    "application/x-www-form-urlencoded");
            // 必须设置false，否则会自动redirect到重定向后的地址
            conn.setInstanceFollowRedirects(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();
            out = (DataOutputStream) conn.getOutputStream();
            out.write(param.getBytes());
            InputStream input = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            String line = "";
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (out != null) {
                out.close();
            }
            if (reader != null) {
                reader.close();
            }
        }
        return result;
    }

    private static String getResultByHttp(String sendUrl, String param)
            throws NoSuchAlgorithmException, KeyManagementException,
            IOException {

        HttpURLConnection conn =null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        String result = "";
        try {

            URL url = new URL(sendUrl);
            conn =(HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            out.write(param.getBytes());
            out.flush();
            out.close();
            InputStream input = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(input,"UTF-8"));
            String line ;
            StringBuffer sb = new StringBuffer();
            while((line=reader.readLine())!=null){
                sb.append(line);
            }
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(reader!=null){
                reader.close();
            }
            out.close();
            conn.disconnect();
        }

        return result;
    }

    public static void main(String[] args) throws Exception {
        String param = "client_id=OjEEU8c8G8&client_secret=07a46c04-9d02-483b-9dba-7f62c4d94acf&code=ST-3-eJZqIFWMI5PR0X74hqMU&redirect_uri=http://10.26.200.178:8080/CallbackServlet&grant_type=authorization_code&oauth_timestamp=1530350311086";
        String url = "https://iam.dpca/profile/oauth2/accessToken";
        System.out.println(getResult(url, param));
    }
}
